//+------------------------------------------------------------------+
//|                                                  LinRegSlope.mq4 |
//|                                                                  |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "fxtraderusa"
#property link      ""

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 Red
//---- input parameters
extern int       Price=0;
extern int       Periods=25;
//---- buffers
double LRS[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
  {
//---- indicators
   SetIndexStyle(0,DRAW_LINE);
   SetIndexBuffer(0,LRS);
   //SetIndexDrawBegin(0,Periods);

//----
   return(0);
  }
//+------------------------------------------------------------------+
//| Custor indicator deinitialization function                       |
//+------------------------------------------------------------------+
int deinit()
  {
//---- 
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int start()
  {
   int    i,counted_bars=IndicatorCounted();   
   double sum_xy, sum_x, sum_y, sum_xx;
   double numerator, denominator;
   
//----
   if(Bars<=2*Periods+1) return(0);
   
//---- initial zero
   if(counted_bars<1)
     {
      for(i=1;i<=Periods;i++) LRS[Bars-i]=0.0;     
     }
         
//---- last counted bar will be recounted
   int limit=Bars-counted_bars;
   if(counted_bars>0) limit++;
   
//---- calculating these new bars only   
   for(i=0; i<limit; i++)
   {
      // Sum(xy): x=j, y=Price
      sum_xy = 0; sum_x = 0; sum_y = 0;
      sum_xx = 0; 
      for (int j=0; j<Periods; j++)
      {
         double y = iClose(NULL,0,i+j);
         double x = Periods - j;
         
         sum_xy += x*y;       
         sum_x += x;
         sum_y += y;
         sum_xx += x*x;
      }
      numerator = Periods*sum_xy - sum_x*sum_y;
      denominator = Periods*sum_xx  - sum_x*sum_x;
      
      if (denominator != 0) 
         LRS[i] = numerator / denominator;   
      else
         LRS[i] = 0.0;
   } // end FOR
   
      
//----
   return(0);
  }
//+------------------------------------------------------------------+